package cronTask

import (
	"arabApi/app/api/services/CronService"
	"arabApi/pkg/pkgCron"
	"errors"
	"fmt"
	"reflect"
)

var ReginCronStruct = make(map[string]interface{})

type CronMap interface {
	RunCron() func()
}

func CronStart() {
	jobList := CronService.List()
	for _, v := range jobList {
		if v.State == 1 {
			if id, err := CronAdd(v.Name, v.Spec); err != nil {
				fmt.Println("定时任务开启", id, err.Error())
			}
		} else {
			fmt.Println("任务状态为不执行" + v.Name)
		}
	}
}

func CronDel(id int) {
	pkgCron.DelFunc(id)
	fmt.Println("定时任务关闭", id)
}

func CronAdd(jobName string, spec string) (int, error) {
	job, ok := ReginCronStruct[jobName]
	if ok {
		t := reflect.TypeOf(job).Elem()
		n := reflect.New(t).Interface().(CronMap)
		id, err := pkgCron.AddFunc(spec, n.RunCron())
		return int(id), err
	} else {
		return 0, errors.New("未找到对应的结构体")
	}
}
